import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import * as api from '../utils/api';
import { logout } from '../utils/auth';
import { TournamentState, TournamentConfig, TournamentRound, AvailableRound } from '../types';
import NotificationModal, { NotificationType } from '../components/NotificationModal';

const TournamentControlPage: React.FC = () => {
  const navigate = useNavigate();
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [availableRounds, setAvailableRounds] = useState<AvailableRound[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSettingRound, setIsSettingRound] = useState(false);
  const [isControllingDraw, setIsControllingDraw] = useState(false);

  // 通知模态框状态
  const [notificationModal, setNotificationModal] = useState<{
    isOpen: boolean;
    type: NotificationType;
    title: string;
    message: string;
  }>({
    isOpen: false,
    type: 'info',
    title: '',
    message: ''
  });

  useEffect(() => {
    loadTournamentData();
  }, []);

  const loadTournamentData = async () => {
    try {
      setLoading(true);
      const [statusResponse, configResponse, availableRoundsResponse] = await Promise.all([
        api.getTournamentStatus(),
        api.getTournamentConfig(),
        api.getAvailableNextRounds()
      ]);

      if (statusResponse.success && statusResponse.tournament_state) {
        setTournamentState(statusResponse.tournament_state);
      }

      if (configResponse.success && configResponse.config) {
        setTournamentConfig(configResponse.config);
      }

      if (availableRoundsResponse.success && availableRoundsResponse.available_rounds) {
        setAvailableRounds(availableRoundsResponse.available_rounds);
      }

      setError(null);
    } catch (err) {
      setError('加载比赛数据失败');
      console.error('加载比赛数据失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const getRoundDisplayName = (round: TournamentRound): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round;
  };

  // 显示通知的辅助函数
  const showNotification = (type: NotificationType, title: string, message: string) => {
    setNotificationModal({
      isOpen: true,
      type,
      title,
      message
    });
  };

  const closeNotification = () => {
    setNotificationModal(prev => ({ ...prev, isOpen: false }));
  };

  const handleSetCurrentRound = async (roundName: string) => {
    try {
      setIsSettingRound(true);
      setError(null);

      const response = await api.setCurrentRound(roundName);
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
        // 重新加载可用轮次
        const availableRoundsResponse = await api.getAvailableNextRounds();
        if (availableRoundsResponse.success && availableRoundsResponse.available_rounds) {
          setAvailableRounds(availableRoundsResponse.available_rounds);
        }
      } else {
        setError(response.error || '设置当前轮次失败');
      }
    } catch (err) {
      setError('设置当前轮次失败');
      console.error('设置当前轮次失败:', err);
    } finally {
      setIsSettingRound(false);
    }
  };

  const handleEnableDrawForRound = async (roundName: string) => {
    try {
      setIsControllingDraw(true);
      setError(null);

      const response = await api.enableDrawForRound(roundName);
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
      } else {
        setError(response.error || '开启抽签失败');
      }
    } catch (err) {
      setError('开启抽签失败');
      console.error('开启抽签失败:', err);
    } finally {
      setIsControllingDraw(false);
    }
  };

  const handleDisableDraw = async () => {
    try {
      setIsControllingDraw(true);
      setError(null);

      const response = await api.disableDraw();
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
      } else {
        setError(response.error || '关闭抽签失败');
      }
    } catch (err) {
      setError('关闭抽签失败');
      console.error('关闭抽签失败:', err);
    } finally {
      setIsControllingDraw(false);
    }
  };

  const handleLogout = () => {
    if (confirm('确定要登出吗？')) {
      logout();
      window.location.reload(); // 刷新页面以触发认证检查
    }
  };

  const handleCheckByeAdvancement = async () => {
    try {
      setIsControllingDraw(true);
      setError(null);

      if (!tournamentState?.draw_stage) {
        setError('当前没有进行中的抽签阶段');
        return;
      }

      const response = await api.checkByeAdvancement(tournamentState.draw_stage);
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
        // 显示成功消息
        showNotification('success', '操作成功', '轮空晋级检查完成！');
      } else {
        setError(response.error || '轮空晋级检查失败');
      }
    } catch (err) {
      setError('轮空晋级检查失败');
      console.error('轮空晋级检查失败:', err);
    } finally {
      setIsControllingDraw(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  if (!tournamentState || !tournamentConfig) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">比赛数据加载失败</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-6xl mx-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => navigate('/tournament')}
              className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
            >
              ← 返回
            </button>
            <h1 className="text-3xl font-bold text-white">比赛控制台</h1>
          </div>
          <div className="flex space-x-2">
            <button
              onClick={loadTournamentData}
              disabled={loading}
              className="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
            >
              刷新状态
            </button>
            <button
              onClick={handleLogout}
              className="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
            >
              登出
            </button>
          </div>
        </div>

        {/* 错误信息 */}
        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded mb-6">
            {error}
          </div>
        )}

        {/* 当前状态 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 mb-6">
          <h2 className="text-2xl font-bold text-white mb-4">当前状态</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-white/20 rounded-lg p-4">
              <div className="text-sm text-blue-200">当前轮次</div>
              <div className="text-lg font-semibold text-white">
                {getRoundDisplayName(tournamentState.current_round)}
              </div>
            </div>
            <div className="bg-white/20 rounded-lg p-4">
              <div className="text-sm text-blue-200">抽签状态</div>
              <div className="text-lg font-semibold">
                {tournamentState.draw_enabled ? (
                  <span className="text-green-300">开启中</span>
                ) : (
                  <span className="text-red-300">已关闭</span>
                )}
              </div>
            </div>
            <div className="bg-white/20 rounded-lg p-4">
              <div className="text-sm text-blue-200">已抽签队长</div>
              <div className="text-lg font-semibold text-white">
                {tournamentState.drawn_captains?.length || 0} 人
              </div>
            </div>
          </div>
        </div>

        {/* 轮次控制 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 mb-6">
          <h2 className="text-xl font-bold text-white mb-4">轮次控制</h2>
          <p className="text-blue-200 mb-4">只能向前切换到下一轮，需要当前轮次所有比赛完成：</p>

          {/* 当前轮次显示 */}
          {tournamentState.current_round && (
            <div className="mb-4 p-4 bg-blue-600/30 rounded-lg border border-blue-400">
              <div className="text-lg font-semibold text-white">
                当前轮次: {getRoundDisplayName(tournamentState.current_round)}
              </div>
              <div className="text-sm text-blue-200 mt-1">
                抽签状态: {tournamentState.draw_enabled ? '已开启' : '已关闭'}
              </div>
            </div>
          )}

          {/* 可切换的下一轮 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {availableRounds.length > 0 ? (
              availableRounds.map((round) => (
                <button
                  key={round.name}
                  onClick={() => handleSetCurrentRound(round.name)}
                  disabled={isSettingRound || !round.can_switch}
                  className={`p-4 rounded-lg font-bold transition-colors duration-200 ${
                    round.can_switch
                      ? 'bg-green-600 hover:bg-green-700 text-white'
                      : 'bg-gray-600 text-gray-300 cursor-not-allowed'
                  }`}
                >
                  <div className="text-lg">{round.display_name}</div>
                  <div className="text-sm opacity-75">
                    {round.type === 'main' ? '主要比赛' :
                     round.type === 'revival' ? '复活赛' : '决赛'}
                    {round.name === 'final' && ' (自动配对)'}
                  </div>
                  <div className={`text-xs mt-1 ${round.can_switch ? 'text-green-200' : 'text-red-200'}`}>
                    {round.reason}
                  </div>
                  {round.type === 'revival' && (
                    <div className="text-xs text-yellow-200 mt-1">仅限上轮淘汰者参加</div>
                  )}
                </button>
              ))
            ) : (
              <div className="col-span-full text-center text-gray-300 py-8">
                {tournamentState.current_round ? '暂无可切换的轮次' : '请先注册队伍'}
              </div>
            )}
          </div>
        </div>

        {/* 抽签控制 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
          <h2 className="text-xl font-bold text-white mb-4">抽签控制</h2>
          
          {/* 开启抽签按钮 */}
          <div className="mb-6">
            <p className="text-blue-200 mb-4">为指定轮次开启抽签：</p>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
              {tournamentConfig.rounds.map((roundConfig) => (
                <button
                  key={`draw-${roundConfig.name}`}
                  onClick={() => handleEnableDrawForRound(roundConfig.name)}
                  disabled={isControllingDraw}
                  className={`${
                    roundConfig.name === 'final'
                      ? 'bg-yellow-600 hover:bg-yellow-700'
                      : 'bg-green-600 hover:bg-green-700'
                  } disabled:bg-gray-600 text-white font-bold py-3 px-4 rounded-lg transition-colors duration-200`}
                >
                  <div className="text-sm">
                    {roundConfig.name === 'final' ? '开启决赛' : '开启抽签'}
                  </div>
                  <div className="text-lg">{roundConfig.display_name}</div>
                  {roundConfig.name === 'final' && (
                    <div className="text-xs text-yellow-200 mt-1">自动配对</div>
                  )}
                </button>
              ))}
            </div>
          </div>

          {/* 关闭抽签按钮 */}
          <div className="mb-6">
            <div className="flex flex-wrap gap-4">
              <button
                onClick={handleDisableDraw}
                disabled={isControllingDraw}
                className="bg-orange-600 hover:bg-orange-700 disabled:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg transition-colors duration-200"
              >
                {isControllingDraw ? '处理中...' : '关闭所有抽签'}
              </button>

              {/* 轮空晋级检查按钮 */}
              {tournamentState.draw_stage && tournamentConfig.rounds.find(r => r.name === tournamentState.draw_stage && r.type === 'revival') && (
                <button
                  onClick={handleCheckByeAdvancement}
                  disabled={isControllingDraw}
                  className="bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg transition-colors duration-200"
                >
                  {isControllingDraw ? '检查中...' : '检查轮空晋级'}
                </button>
              )}
            </div>
            <p className="text-blue-200 text-sm mt-2">
              轮空晋级检查：复活赛抽签结束后，自动处理只有一支队伍的组别，让该队伍轮空晋级
            </p>
          </div>

          {/* 抽签状态显示 */}
          <div className="bg-white/20 rounded-lg p-4">
            <div className="text-sm text-white mb-2">
              抽签状态: {tournamentState.draw_enabled ? (
                <span className="text-green-300">
                  开启中 ({getRoundDisplayName(tournamentState.draw_stage as TournamentRound)})
                </span>
              ) : (
                <span className="text-red-300">已关闭</span>
              )}
            </div>
            <div className="text-sm text-blue-200">
              已抽签队长: {tournamentState.drawn_captains?.length || 0} 人
            </div>
            {tournamentState.drawn_captains && tournamentState.drawn_captains.length > 0 && (
              <div className="text-xs text-gray-300 mt-2">
                {tournamentState.drawn_captains.join(', ')}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 通知模态框 */}
      <NotificationModal
        isOpen={notificationModal.isOpen}
        onClose={closeNotification}
        type={notificationModal.type}
        title={notificationModal.title}
        message={notificationModal.message}
      />
    </div>
  );
};

export default TournamentControlPage;
